// pages/groupCourse/groupCourse.js
var app = getApp();
var util=require("../../utils/util");
var home=require("../../api/home");
var config=require("../../api/config");
var group=require("../../api/group");

Page({
  data: {
    id: '',
    info: '',
    navColor: 'rgba(0,0,0,0)',
    title: '',
    labelName: '',
    back_type: 1,
    banner_list: [1,2,3],
    current_index: 0,
    day: 0,
    hour: 0,
    minute: 0,
    second: 0,
    rule_list: ['选择拼团课程','开团或者参团','支付拼团定金','等待好友参团','达到人数拼团成功'],
    rule_index: 0,
    scroll_top: [],
    toView: '',
    bar_text: ["课程套餐","拼团规则","正在拼团","授课老师","课程评价","课程机构","课程详情","购买须知"],
    bar_index: 0,
    fix: false,
    pop_show: true,
    com_data: [],
    show_com: 0,
    comment_list: [],
    pref_list: [],
    currentPage: 1,
    pageSize: 10,
    hasMoreDate: true,
    latitude: 22.820794,
    longitude: 113.284565,
    token: '',
    userinfo: '',
    diff_height: 0,
    timeGroup: '',
    endTime: {day: '00',hour: '00',minute: '00',second: '00'},
    status_show: true,
    status_text: ''
  },
  /*生命周期函数--监听页面加载*/
  onLoad: function (options) {
    // console.log(options)
    var that=this,id='',type=1;
    if(options.scene){
      var sence=decodeURIComponent(options.scene).split("I");
      id=sence[0];
      type=sence[1];
    }else{
      id=options.id;
      type=options.type?options.type:type;
    }
    var sysInfo = wx.getSystemInfoSync();
    var pixelRate = sysInfo.windowWidth / 750,times=sysInfo.windowWidth/375;
    that.setData({id:id,back_type:type,top_height: (sysInfo.statusBarHeight+44)/pixelRate,times:times,width: sysInfo.windowWidth});
    wx.getStorage({
      key: 'city',
      success:function(res){
        var info=res.data;
        that.setData({latitude:info.lat,longitude:info.lng})
        that.get_cour_and_group(id)
      },
      fail:function(){
        that.get_cour_and_group(id)
      },
    })
    //
    that.group_browse(id)
  },
  // 轮播图
  swiper_change:function(e){
    this.setData({current_index: e.detail.current})
  },
  // 放大预览图片
  preview_img:function(e){
    var that=this,info=that.data.info;
    var src=e.currentTarget.dataset.src;
    wx.previewImage({
      current: src,
      urls: info.course.swipers
    })
  },
  // 页面滚动
  page_scroll:function(e){
    var that = this,scroll_top = that.data.scroll_top,top_height = that.data.top_height,bar_index=that.data.bar_index,diff_height=that.data.diff_height,scroll_index=that.data.bar_index;
    var scroll = e.detail.scrollTop,info=that.data.info;
    // console.log(scroll)
    if(scroll >= 160){
      that.setData({navColor:'#ffffff',title:info.course.name,labelName:info.activityGroup.activityLabelNames})
    }else{
      that.setData({navColor:'rgba(0,0,0,0)',title:'',labelName:''})
    }
    if(scroll_top.length>0){
      if(scroll>=(scroll_top[0].top-top_height)){
        if(!that.data.fix){
          that.setData({fix: !that.data.fix})
        }
      }else{
        if(that.data.fix){
          that.setData({fix: !that.data.fix})
        }
      }
      for (var i = 0; i < scroll_top.length; i++) {
        if ((i + 1) < scroll_top.length&&i>0) {
          if (scroll > (scroll_top[i-1].top-diff_height) && scroll < (scroll_top[i].top-diff_height)) {
            scroll_index=i
          }
        }
        if (scroll < scroll_top[0].top-diff_height) {
          scroll_index=0
        }
      }
    }
    that.setData({ bar_index: scroll_index })
    if(bar_index!=scroll_index){
      that.scroll_to_left(scroll_index)
    }
  },
  // 顶部导航
  scroll_page_to:function(e){
    var that = this,bar_index=that.data.bar_index,bar_text=that.data.bar_text,scroll_top=that.data.scroll_top;
    var index = e.currentTarget.dataset.index;
    if(bar_index != index){
      that.setData({bar_index:index})
      if(index==(bar_text.length-1)){
        that.setData({scroll_to_top:scroll_top[index].top})
      }else{
        that.setData({toView:"item"+(index+1)})
      }
    }
    //切换
    that.scroll_to_left(index)
  },
  // 顶部导航滑动
  scroll_to_left:function(index){
    var that=this,len=that.data.bar_text.length;
    if(len >= 3){
      var curWidth = (that.data.width - 30) / 4.5;
      var moveWidth = (index - 1) * curWidth
      if (moveWidth > 0) {
        that.setData({ scrollLeft: parseInt(moveWidth)})
      } else {
        that.setData({ scrollLeft: 0 })
      }
    }
  },
  // 渲染完成
  onReady: function () {
    this.dialog = this.selectComponent('#courpop');
  },
  // 分享
  onShareAppMessage:function(e){
    var that=this,info=that.data.info;
    if(info){that.group_share(info.activityGroup.id)}
    return{
      title: info.course.name,
      path: '/pages/groupCourse/groupCourse?id='+info.activityGroup.id+'&type=2',
      imageUrl: info.course.swipers[0]
    }
  },
  onShareTimeline:function(){
    var that=this,info=that.data.info;
    return{
      title: info.course.name,
      query: 'id='+info.activityGroup.id+'&type=2',
      imageUrl: info.course.swipers[0]
    }
  },
  // 刷新
  onShow:function(){
    var that=this,token=that.data.token,id=that.data.id,info=that.data.info;
    var token_again=wx.getStorageSync('token'),userinfo=wx.getStorageSync('userinfo');
    if(!token&&token_again){
      that.setData({token: token_again,userinfo:userinfo})
    }
    if(app.globalData.login||app.globalData.change_courMeal){
      that.get_cour_and_group(id)
      app.globalData.login=false;
      app.globalData.change_courMeal=false;
    }
    if(info){
      that.setInterval_time();
    }
  },
  onHide:function(){
    clearInterval(this.data.timeGroup)
  },
  onUnload:function(){
    clearInterval(this.data.timeGroup)
  },
  setInterval_time:function(){
    var that=this,info=that.data.info;
    that.data.timeGroup=setInterval(function(){
      var stepTime= info.activityGroup.activityEndTime/1000-parseInt(new Date().getTime())/1000;
      var endTime=util.time4date(stepTime);
      if(stepTime>0){
        that.setData({endTime:endTime})
      }else{
        clearInterval(that.data.timeGroup)
      }
    },1000)
  },
  // 弹窗
  open_courpop:function(e){
    var that = this,info=that.data.info;
    var num = e.currentTarget.dataset.num;
    //
    that.setData({show_com:num,pop_show: !that.data.pop_show})
    if(num==1){
      that.setData({com_data:that.data.pref_list,currentPage:1})
    }else if(num==2){
      var info_data={score:'',commentCount:''};
      info_data.score=info.course.sumScore,info_data.commentCount=info.course.commentCount
      that.setData({com_data:that.data.comment_list,info_data:info_data,currentPage:1})
    }else if(num==3){
      that.setData({com_data:info.courseProtocolTemplate})
    }else if(num==4){
      that.setData({com_data:info.course.courseSetMeals})
    }else if(num==6){
      that.setData({com_data:info.groupFounds})
    }
  },
  close_pop:function(e){
    var that = this;
    var obj = e.detail.pop_show;
    that.setData({pop_show: obj})
  },
  // 
  nav_detail:function(){
    wx.navigateTo({
      url: '../courDet/courDet',
    })
  },
  // 领取优惠卷
  get_pref:function(e){
    var that=this,pref_list=that.data.pref_list,token=that.data.token;
    var index=e.detail.index;
    if(pref_list[index].isReceive!=1){
      if(token){
        //
        that.user_get_pref(index,token)
      }else{
        wx.navigateTo({
          url: '../login/login',
        })
        that.setData({pop_show: true,pref_list:[]})
      }
    }
  },
  // 联系
  call_phone:function(){
    var that=this,info=that.data.info;
    wx.makePhoneCall({
      phoneNumber: info.business.serverPhone,
      success:function(){},
      fail:function(){}
    })
  },
   // 老师
   nav_famous:function(){
    var that=this,info=that.data.info;
    if(info.course.teacherId){
      wx.navigateTo({
        url: '../famousDetail/famousDetail?uid='+info.course.teacherId+'&oid='+info.course.businessId+'&type=4',
      })
    }
  },
  // 机构
  nav_go_mech:function(){
    var that=this,info=that.data.info;
    wx.navigateTo({
      url: '../mechDetail/mechDetail?id='+info.course.businessId+'&status=2',
    })
  },
  // 支付/拼团    type 1-单独报名 2-定金开团 3-团购价开团 4-定金参团 5-团购价参团
  nav_pay_group:function(e){
    var that=this,token=that.data.token,info=that.data.info,group_aid=that.data.id;
    var id=e.currentTarget.dataset.id,type=e.currentTarget.dataset.type;
    if(token){
      if(type==4||type==5){
        var group_id=e.currentTarget.dataset.group;
        wx.navigateTo({
          url: '../payCourse/payCourse?id='+id+'&lessonTime='+info.course.lessonTime+'&type='+type+'&group_id='+group_id+'&group_aid='+group_aid,
        })
      }else{
        if(type==1&&info.setMeal.count<=0){
          return false;
        }
        wx.navigateTo({
          url: '../payCourse/payCourse?id='+id+'&lessonTime='+info.course.lessonTime+'&type='+type+'&group_aid='+group_aid,
        })
      }
    }else{
      wx.navigateTo({
        url: '../login/login',
      })
    }
  },
  // 路线
  open_location:function(){
    var that=this,info=that.data.info;
    wx.openLocation({
      latitude: info.business.lat,
      longitude: info.business.lng,
      name: info.business.name,
      address: info.business.detail?(info.business.detail.indexOf("省")>0?info.business.detail:info.business.province+info.business.city+info.business.region+info.business.town+info.business.detail):info.business.province+info.business.city+info.business.region+info.business.town+info.business.detail,
      success:function(res){
        console.log('---路线---')
      }
    })
  },
  return:function(){},
  // 触底
  scroll_bottom:function(e){
    var that=this,id=that.data.id,hasMoreData=that.data.hasMoreData;
    var type=e.detail;
    if(hasMoreData){
      if(type==1){
        console.log("---拼团还会有优惠券吗!---")
      }else{
        that.get_cour_comment(id,1)
      }
    }else{
      util.page_show_toast('没有更多了',1500)
    }
  },
  // 收藏
  user_call_cour:function(){
    var that=this,info=that.data.info,token=that.data.token;
    if(token){
      if(!info.collection){
        info.collection=true
        info.course.collectionCount +=1
        that.call_cour(info.course.id,true,token)
      }else{
        info.collection=false
        info.course.collectionCount -=1
        that.call_cour(info.course.id,false,token)
      }
      that.setData({info:info})
    }else{
      wx.navigateTo({
        url: '../login/login',
      })
    }
  },
  // 拼团活动详情
  get_cour_and_group:function(id){
    wx.showLoading({title: '加载中'})
    var that=this,rule_list=that.data.rule_list;
    var params={
      "id":id,
      "lat": that.data.latitude,
      "lng": that.data.longitude
    }
    group.get_cour_and_group(params).then(res=>{
      if(res.data.code==200){
        if(res.data.data){
          var info=res.data.data;
          info.course.sumScore=info.course.sumScore?info.course.sumScore.toFixed(1):'5.0';
          info.course.swipers=info.course.introducePictures?info.course.introducePictures.split(","):'';
          info.course.courseNatureName=info.course.courseNatureName?info.course.courseNatureName.substr(0,2):''
          info.course.labelName=info.course.labelName?info.course.labelName.split(","):'';
          info.course.teacherProfile=info.course.teacherProfile?(info.course.teacherProfile.indexOf("undefined")>-1?'':info.course.teacherProfile.split(",")):'';
          info.course.collectionCount=info.course.collectionCount?info.course.collectionCount:0;
          info.course.commentCount=info.course.commentCount?info.course.commentCount:0;
          info.activityGroup.groupPrice=info.activityGroup.groupPrice?util.toDecimal(info.activityGroup.groupPrice):0;
          info.activityGroup.setMealPrice=info.activityGroup.setMealPrice?util.toDecimal(info.activityGroup.setMealPrice):0
          info.activityGroup.deposit=info.activityGroup.deposit?util.toDecimal(info.activityGroup.deposit):0
          info.activityGroup.partakeCount=info.activityGroup.partakeCount?info.activityGroup.partakeCount:0
          info.activityGroup.virtualGroupCount=info.activityGroup.virtualGroupCount?info.activityGroup.virtualGroupCount:0
          info.activityGroup.totalCount=info.activityGroup.partakeCount+info.activityGroup.virtualGroupCount;
          info.business.space=info.business.distance>1000?(info.business.distance/1000).toFixed(2):info.business.distance;
          info.business.labels=info.business.labels?info.business.labels.split(","):'';
          info.course.initialRegistrationCount=info.course.initialRegistrationCount?info.course.initialRegistrationCount:0;
          if(info.setMeal.maxQuantity){
            info.setMeal.count=info.setMeal.maxQuantity-info.setMeal.sellCount;
          }else{
            info.setMeal.count=1;
          }
          var details=info.course.details?info.course.details:'';
          if(details){
            if(details.indexOf('img')>-1){
              details=details.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
            }
            if(details.indexOf('<style>')>-1){
              details=details.replace(/<style>[\s\S]*?<\/style>/ig,'')
            }
          }
          if(info.activityGroup.status!=2){
            var text=info.activityGroup.status==1?'活动未开始':'活动已结束'
            that.setData({status_show: false,status_text:text})
          }
          if(info.activityGroup.isDeposit!=1){
            rule_list[2]="支付完成"
            that.setData({rule_list:rule_list})
          }
          info.course.details=details;
          var group_list=info.groupFounds,arr=[];
          if(group_list.length>0){
            group_list.map(item=>{
              item.lessonTime=info.course.lessonTime;
              item.isDeposit=info.activityGroup.isDeposit;
              var endTime=item.endTime-new Date().getTime();
              if(item.surplusCount>0&&endTime>0){
                arr.push(item)
              }
            })
          }
          info.groupFounds=arr;
          //
          that.get_grade_list(info)
        }else{
          util.page_show_toast('课程已下架',1500)
        }
      }
    })
  },
  // 适用年级
  get_grade_list:function(cour_info){
    var that=this,info=cour_info;
    config.get_grade_list().then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        for(var i=0;i<list.length;i++){
          for(var j=0;j<list[i].gradeList.length;j++){
            if(info.course.gradeBegin==list[i].gradeList[j].value){
              info.course.gradeBeginName=list[i].gradeList[j].text
            }
            if(info.course.gradeEnd==list[i].gradeList[j].value){
              info.course.gradeEndName=list[i].gradeList[j].text
            }
          }
        }
        that.setData({info:info,pref_list:[],diff_height:info.course.lableName?'30':'60'})
        setTimeout(()=>{
          var query = wx.createSelectorQuery();
          query.selectAll('.page_scroll').boundingClientRect(function (res) {
            // console.log(res)
            that.setData({scroll_top: res})
          }).exec()
        },600)
        //
        that.get_cour_comment(info.course.id,0);
        var cour_details={id:info.course.id,img:info.course.swipers[0],name:info.course.name,courseNatureName:info.course.courseNatureName,gradeBeginName:info.course.gradeBeginName,gradeEndName:info.course.gradeEndName,count:info.course.initialRegistrationCount,isAgeLimit:info.course.isAgeLimit,details:info.course.details,activityId:info.activityGroup.id,setMealPrice:info.setMeal.price,groupPrice:info.activityGroup.groupPrice,deposit:info.activityGroup.deposit,isDeposit:info.activityGroup.isDeposit,lessonTime:info.course.lessonTime,setMealId:info.activityGroup.setMealId,labelName:info.activityGroup.activityLabelNames};
        wx.setStorageSync('cour_details', cour_details)
        that.setInterval_time();
      }
    })
  },
  // 评论列表
  get_cour_comment:function(id,type){
    wx.showLoading({title: '加载中'})
    var that=this,currentPage=that.data.currentPage,pageSize=that.data.pageSize;
    var params={
      "courseId": id,
      "currentPage": currentPage,
      "pageSize": pageSize
    }
    home.get_cour_comment(params).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].createTime=util.formatTime(new Date(list[i].createTime))
          list[i].score_list=["","","","",""]
        }
        var comment_list = that.data.comment_list;
        comment_list = util.extend(comment_list, list)
        if (list.length < pageSize) {
          that.setData({
            comment_list: comment_list,
            hasMoreData: false
          })
        } else {
          that.setData({
            comment_list: comment_list,
            hasMoreData: true,
            currentPage: currentPage + 1
          })
        }
        if(type==1){
          that.setData({com_data: comment_list})
        }
      }
    })
  },
  // 收藏
  call_cour:function(id,like,token){
    wx.showLoading({title: '加载中'})
    var params={"courseId": id,"isLike": like};
    home.call_cour(params,token).then(res=>{
      if(res.data.code==200){
        if(like){
          util.page_show_toast('收藏成功',2000)
        }else{
          util.page_show_toast('取消收藏成功',2000)
        }
      }
    })
  },
  // 分享
  group_share:function(id){
    group.group_share({"activityId":id}).then(res=>{

    })
  },
  // 浏览
  group_browse:function(id){
    group.group_browse({"activityId":id}).then(res=>{

    })
  },
})